<template>
  <div class="view_page userList">
    <el-card class="box-card">
      <!--卡片头部-->
      <div slot="header" class="clearfix">
        <!--左侧-->
        <div class="left">
          <div class="back-page">
            <div class="add-back" @click="back">
              <i class="fa fa-arrow-left" aria-hidden="true"></i>
              <span v-if="addtype == 'add'">添加全景图</span>
              <span v-if="addtype == 'update'">修改全景图</span>
            </div>
          </div>
        </div>
        <!-- 右侧-->
        <div class="right">
          <el-button
            type="primary"
            size="small"
            @click="save"
            v-if="addtype == 'add'||addtype == 'update'"
            >保存
          </el-button>
        </div>
      </div>
      <!-- 卡片内容 -->
      <div>
        <el-form :model="liveData" label-width="200px" class="inline-input">
          <el-form-item label="全景图名称" :required="true">
            <el-input v-model="liveData.title" placeholder=""></el-input>
          </el-form-item>
          <el-form-item label="全景图(png,jpg,jpeg)" :required="true">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :data="uploadData"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :auto-upload="true"
              accept=".png,.jpg,.jpeg"
              :limit="1"
              :on-exceed="numberExceeded"
            >
              <el-button slot="trigger" size="small" type="primary"
                >选取图片
              </el-button>
            </el-upload>
            <div>
              <img
                :src="cover_img"
                alt=""
                v-if="cover_img != '' && cover_img != null"
                style="width: 300px; object-fit: cover;margin-top: 5px;"
              />
            </div>
          </el-form-item>
          <el-form-item label="缩略图(png,jpg,jpeg)" :required="true">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl2"
              :on-preview="handlePreview_sl"
              :on-remove="handleRemove_sl"
              :file-list="fileList_sl"
              :data="uploadData"
              :before-upload="beforeAvatarUpload_sl"
              :on-success="handleAvatarSuccess_sl"
              :on-error="handleAvatarError_sl"
              :auto-upload="true"
              accept=".png,.jpg,.jpeg"
              :limit="1"
              :on-exceed="numberExceeded"
            >
              <el-button slot="trigger" size="small" type="primary"
                >选取图片
              </el-button>
            </el-upload>
            <div>
              <img
                :src="cover_img1"
                alt=""
                v-if="cover_img1 != '' && cover_img1 != null"
                style="width: 300px; object-fit: cover;margin-top: 5px;"
              />
            </div>
          </el-form-item>
          <el-form-item label="经度">
            <el-input
              v-model="liveData.lon"
              clearable
              placeholder="请输入经度"
            ></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input
              v-model="liveData.lat"
              clearable
              placeholder="请输入纬度"
            ></el-input>
          </el-form-item>
          <el-form-item label="拍摄高度(m)">
            <el-input
              v-model="liveData.take_height"
              clearable
              type="number"
              placeholder="请输入拍摄高度"
            ></el-input>
          </el-form-item>
          <el-form-item label="拍摄时间">
            <el-date-picker
              type="datetime"
              placeholder="请选择拍摄时间"
              style="width: 100%"
              v-model="liveData.shoot_time"
              @change="changeDatetime"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="选择地区">
            <el-cascader
              class="cascader"
              v-model="selelected2"
              :options="area"
              :props="props2"
              clearable
              ref="areaRef"
              @change="changeArea"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="选择工程">
            <el-cascader
              class="cascader"
              v-model="selelected"
              :options="options"
              :props="props"
              clearable
              :popper-class="'hide'"
              @change="changeCity"
              ref="cascade"
            ></el-cascader>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { Message } from "element-ui";
import pagination from "@/components/common/pagination/pagination";
import devConfig from "*/dev.config";
import Utils from "@/utils/index";

export default {
  components: {
    pagination
  },
  watch: {},
  data() {
    return {
      // userInfo: this.$apis.getqxbutton("分类管理"),
      // userInfo_id: JSON.parse(
      //   localStorage.getItem(this.$apis.getLocalKey().loginPersonnelInformation)
      // ).data.id,
      // 筛选内容
      liveData: {
        title: "",
        file: "",
        file_thumb: "",
        river_type: "",
        river_id: "",
        river1: "",
        river2: "",
        selelected: "",
        lon:'',
        lat:'',
        take_height:'',
        shoot_time:'',
      },
      dialogVisible: false, //添加栏目弹框
      addtype: "", //类型 新增-修改

      // 选择工程
      // options: [],
      // props: {
      //   multiple: true,
      //   expandTrigger: "click"
      // },
      area: [],
      props2: {
        multiple: true,
        expandTrigger: "click"
      },
      // selelected: [],
      selelected2: [],

      // 列表的数据
      datalist: [],
      allIndex: "",
      pageNum: 1,
      page: 1,
      size: 10,
      total: 0,

      // uploadUrl: "https://dongping.jnaw.top/smxc/file/upload",
      uploadUrl: `${this.$apis.getUploadUrl()}/file/upload/qjt`,
      uploadUrl2: `${this.$apis.getUploadUrl()}/file/upload`,
      // uploadUrl: this.$apis.getUploadUrl() + "/file/upload", //上传地址
      uploadData: {
        type: 1 //没用
      },
      fileList: [],
      file_id: "",
      // addtype: "",
      cover_img: "",
      cover_img1: "",
      file_suffix: "",
      fileList_sl: [],

      preValue: [],

      selelected: [],
      options: [],
      props: {
        expandTrigger: "click",
        multiple: true,
        checkStrictly: false,
        value: "value",
        label: "label"
      }
    };
  },
  created() {
    var _this = this;
    this.addtype = this.$route.query.type;
    this.village_list();
    _this.getoptionsData(); //选择工程级联列表
    _this.getareaData(); //选择地区级联列表

    if (this.addtype == "update") {
      var alldata = JSON.parse(JSON.stringify(this.$route.query.data));
      this.liveData = alldata;

      // 地区级联列表回显
      let twoDArray2 = [];
      twoDArray2 = _this.liveData.json_rivers.map((item, index) => {
        return ([index] = [item.river_type, item.river_id]);
      });
      _this.selelected2 = twoDArray2;

      // 工程级联列表回显
      let twoDArray = [];
      twoDArray = _this.liveData.json_pro.map((item, index) => {
        return ([index] = [item.pro_type, item.pro_id]);
      });
      _this.selelected = twoDArray;

      // console.log(_this.$route.query)
      this.liveData.river_type = this.$route.query.data.river1;
      this.liveData.river_id = this.$route.query.data.river2;

      this.cover_img = this.$route.query.data.url;
      this.cover_img1 = this.$route.query.data.url_thumb;
      this.file_id = this.$route.query.data.file;
      this.file_sl_id = this.$route.query.data.file_thumb;
      this.fileList = [
        {
          id: this.$route.query.data.file,
          name: this.$route.query.data.file_name,
          url: this.$route.query.data.url
        }
      ];
      this.fileList_sl = [
        {
          id: this.$route.query.data.file_thumb,
          name: this.$route.query.data.file_thumb_name,
          url: this.$route.query.data.url_thumb
        }
      ];
    }
  },
  mounted() {},
  methods: {
    changeDatetime(){
      this.liveData.shoot_time = Utils.formatDateTime(this.liveData.shoot_time);
    },
    // 选择地区级联列表
    getareaData() {
      var _this = this;
      _this.$apis.unitywebpc_address_list().then(res => {
        if (res.result == 0) {
          _this.area = res.data;
        }
      });
    },
    // 选择工程级联列表
    getoptionsData() {
      var _this = this;
      _this.$apis.unitywebpc_engine_list().then(res => {
        if (res.result == 0) {
          _this.options = res.data;
        }
      });
    },
    // 地区级联选择
    changeArea(items) {
      let itemArr2 = [];
      this.$refs["areaRef"].getCheckedNodes(items).map(item => {
        itemArr2.push({
          river_type: item.pathNodes[0].value,
          river_id: item.pathNodes[1].value,
          name: item.pathLabels[0],
          river_name: item.pathLabels[1]
        });
      });
      this.liveData.json_rivers = itemArr2;
    },
    // 工程级联选择
    changeCity(items) {
      let itemArr = [];
      this.$refs["cascade"].getCheckedNodes(items).map(item => {
        itemArr.push({
          pro_type: item.pathNodes[0].value,
          pro_id: item.pathNodes[1].value,
          name: item.pathLabels[0],
          pro_name: item.pathLabels[1]
        });
      });
      this.liveData.json_pro = itemArr;
    },

    village_list() {
      this.$apis.unitywebpc_engine_list().then(res => {
        if (res.result == 0) {
          let tt = res.data;
          this.options = tt;
        }
      });
    },

    save() {
      var _this = this;
      var datas = JSON.parse(JSON.stringify(this.liveData));

      if (datas.title == "") {
        Message.error("全景图名称不能为空");
        return;
      }
      if (this.fileList.length == 0) {
        Message.error("全景图不能为空");
        return;
      }
      datas.file = _this.file_id;
      if (this.fileList_sl.length == 0) {
        Message.error("缩略图不能为空");
        return;
      }
      datas.file_thumb = _this.file_sl_id;
      // if (datas.lon == '') {
      //   Message.error("经度不能为空");
      //   return;
      // }
      // if (datas.lat == '') {
      //   Message.error("纬度不能为空");
      //   return;
      // }
      // if (datas.take_height == '') {
      //   Message.error("拍摄高度不能为空");
      //   return;
      // }
      // if (datas.shoot_time == '') {
      //   Message.error("拍摄时间不能为空");
      //   return;
      // }

      if (this.selelected2.length == 0&&this.selelected.length==0) {
        Message.error("请至少选择一个工程/地区");
        return;
      }

      // 选择地区
      // if (_this.selelected2.length == 0) {
      //   Message.error("选择地区不能为空");
      //   return;
      // }
      datas.json_rivers = JSON.stringify(_this.liveData.json_rivers);
      // 选择工程
      // if (_this.selelected.length == 0) {
      //   Message.error("选择工程不能为空");
      //   return;
      // }
      datas.json_pro = JSON.stringify(_this.liveData.json_pro);

      console.log("datas:", datas);
      if (this.addtype == "add") {
        _this.$apis.panorama_unity_batch_add(datas).then(res => {
          if (res.result == 0) {
            Message.success("添加成功");
            _this.$router.back();
          }
        });
      } else {
        datas.id = this.$route.query.data.id;
        _this.$apis.panorama_unity_batch_update(datas).then(res => {
          if (res.result == 0) {
            Message.success("修改成功");
            _this.$router.back();
          }
        });
      }
    },

    download() {
      window.open("https://xiaoyoushengxue.com/2022051218194530.xlsx");
    },
    downloaddata() {
      var _this = this;

      window.open(
        devConfig.apiPrefix +
          "/excel/user_all_export?user_role=" +
          _this.TESTFROMDATA.type
      );
    },
    back() {
      this.$router.back();
    },
    //上传文件
    submitUpload() {
      // if (JSON.stringify(this.fileList)=='[]') {
      //   Message.warning('请上传图片')
      //   return
      // }
      this.$refs.upload.submit();
    },
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log("handleRemove===========", file, fileList);
      this.file_id = "";
      this.fileList = fileList;
      this.cover_img = "";

      // if (this.addtype == "add") {
      // 	this.cover_img = "";
      // } else {
      // 	this.cover_img = this.$route.query.data.river_img;
      // 	this.file_id = this.$route.query.data.river_img_id;
      // }
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    //文件上传成功的钩子
    handleAvatarSuccess(res, file, fileList) {
      // this.cover_img = res.data.url;
      // this.file_id = res.data.id;
      // this.fileList = fileList;

      if (res.result == 0) {
        // _this.cover_img = res.data.url;
        this.cover_img = res.data.url_thumb
        this.file_id = res.data.id
        this.fileList = fileList
        // _this.imageUrl = URL.createObjectURL(file.raw)

        // 详细信息  经度、纬度、高度
        if (res.data.info) {
          console.log('=====图片信息======',res.data.info)
          this.liveData.lon = res.data.info.longitude||'';
          this.liveData.lat = res.data.info.latitude||'';
          this.liveData.take_height = res.data.info.height.slice(0, -7)||'';
          let shoot_time = res.data.info.shotTime||'';
          if(shoot_time){
            shoot_time = shoot_time.substr(0,4)+'-'+shoot_time.substr(5,2)+'-'+shoot_time.substr(8,2) + ' '+shoot_time.substr(11);
          }
          this.liveData.shoot_time = shoot_time;
        }
      }

      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    //文件上传失败时的钩子
    handleAvatarError(err, file) {
      Message.error("文件上传失败，请稍后再试");
      this.dialogVisible = false;
    },
    //文件超出一个
    numberExceeded() {
      Message.error("只能上传一张图片");
    },
    //上传文件之前的钩子
    beforeAvatarUpload(file) {
      // var typeList = ["image/jpeg", "image/png", "image/jpg","image/tif"];
      // const isJPG = file.type === 'image/jpeg'
      // const isJPG = typeList.includes(file.type);
      // const isLt2M = file.size / 1024 / 1024 < 10;
      // if (!isJPG) {
      // 	this.$message.error("上传图片只能是 JPG或者PNG 格式!");
      // }
      // if (!isLt2M) {
      // 	this.$message.error("上传文件大小不能超过 10MB!");
      // }
      // return isJPG
    },

    //上传缩略图
    submitUpload_sl() {
      // if (JSON.stringify(this.fileList)=='[]') {
      //   Message.warning('请上传图片')
      //   return
      // }
      this.$refs.upload.submit();
    },
    //文件列表移除文件时的钩子
    handleRemove_sl(file, fileList) {
      console.log("handleRemove===========", file, fileList);
      this.file_sl_id = "";
      this.fileList_sl = fileList;
      this.cover_img1 = "";
      // this.item.file_thumb_url = "";

      // if (this.addtype == "add") {
      // 	this.cover_img1 = "";
      // } else {
      // 	this.cover_img1 = this.$route.query.data.river_img;
      // 	this.file_id = this.$route.query.data.river_img_id;
      // }
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview_sl(file) {
      console.log(file);
    },
    //文件上传成功的钩子
    handleAvatarSuccess_sl(res, file, fileList) {
      var _this = this;

      this.cover_img1 = res.data.url;
      // this.item.file_thumb_url = res.data.url;
      // this.file_suffix = res.data.suffix
      this.file_sl_id = res.data.id;
      this.fileList_sl = fileList;

      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    //文件上传失败时的钩子
    handleAvatarError_sl(err, file) {
      Message.error("文件上传失败，请稍后再试");
      this.dialogVisible = false;
    },
    //文件超出一个
    numberExceeded_sl() {
      Message.error("只能上传一张图片");
    },
    //上传文件之前的钩子
    beforeAvatarUpload_sl(file) {
      // var typeList = ["image/jpeg", "image/png", "image/jpg","image/tif"];
      // const isJPG = file.type === 'image/jpeg'
      // const isJPG = typeList.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      // 	this.$message.error("上传图片只能是 JPG或者PNG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
      }
      return isLt2M;
    }
  }
};
</script>

<style scoped>
.el-table .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal !important;
}

/*.hide {
  .el-cascader-menu:first-of-type {
    .el-cascader-node {
      .el-checkbox {
        display: none;
      }
    }
  }
}*/

.el-cascader-panel > div:first-child .el-checkbox {
  display: none;
}
</style>
<style lang="scss" scoped>
/deep/ .el-cascader__tags .el-tag .el-icon-close {
  display: none;
}
</style>
